package com.brother.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.brother.database.DataBase;
import com.brother.model.CarModel;

public class CarModelService {

public void addCarModel(String name,String description,String description_zh){
	description = description.replaceAll("'", "\\\\'");
	description_zh = description_zh.replaceAll("'", "\\\\'");
	String sql = "insert into carmodel(carmodelid,name,description,description_zh) " +
			"values(UUID(),'"+name+"','"+description+"','"+description_zh+"')";
	DataBase.update(sql);
	DataBase.closeConnection();
}

public void modifyCarModel(String carModelId,String name,String description,String description_zh){
	description = description.replaceAll("'", "\\\\'");
	description_zh = description_zh.replaceAll("'", "\\\\'");
	String sql = "update carmodel set name='"+name+"',description='"+description+"',description_zh='"+description_zh+"' " +
			" where carmodelId='"+carModelId+"'";
	DataBase.update(sql);
	DataBase.closeConnection();	
}
	
public CarModel getCarModel(String fieldName,String queryWord){
	CarModel car = null;
	String sql = "select * from carmodel where " + fieldName + "='" + queryWord + "'";
	try {
		ResultSet rs = DataBase.query(sql);
		if(rs.next()){
			car = new CarModel();
			car.setCarmodelId(rs.getString("carmodelid"));
			car.setDescription(rs.getString("description"));
			car.setDescription_zh(rs.getString("description_zh"));
			car.setName(rs.getString("name")); 
		}
	} catch (SQLException e) {
		Logger.getLogger(this.getClass()).error(e);
	}
	DataBase.closeConnection();	
	return car;
}

public List<CarModel> getAllCarModels(){
	List<CarModel> models = new ArrayList<CarModel>();
	String sql = "select * from carmodel";
	
	try {
		ResultSet rs = DataBase.query(sql);
		while(rs.next()){
			CarModel car = new CarModel();
			car.setCarmodelId(rs.getString("carmodelid"));
			car.setDescription(rs.getString("description"));
			car.setName(rs.getString("name"));
			models.add(car);
		}
	} catch (SQLException e) {
		Logger.getLogger(this.getClass()).error(e);
	}	
	DataBase.closeConnection();
	return models;
}

public void deleteCarmodel(String modelid){
	String sql = "delete from carmodel where carmodelid='" + modelid +"'";
	DataBase.update(sql);
	DataBase.closeConnection();
}

}
